import json

from django.shortcuts import render
from rest_framework import status

from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.filters import OrderingFilter

from rest_framework.views import APIView
from goods.models import SKU
from goods.serializers import SKUSerializer,SKUIndexSerializer, OrderListSerializers

from drf_haystack.viewsets import HaystackViewSet
# Create your views here.

# 根据第三级分类ID获取分类SKU商品的数据
# GET /categories/(?P<category_id>\d+)/skus/


# GET /skus/search/?text=<搜索关键字>
from orders.models import OrderGoods, OrderInfo


class SKUSearchViewSet(HaystackViewSet):
    #指定索引类对应模型类
    index_models = [SKU]

    #指定搜索结果序列化时所使用的序列化器类
    #搜索结果中每个对象都包含两个属性
    # text: 索引字段的内容
    # object: 从数据库中搜索出模型对象（此处是SKU模型对象）
    serializer_class = SKUIndexSerializer

class SKUListView(ListAPIView):
    serializer_class = SKUSerializer

    def get_queryset(self):
        '''返回第三级分类ID分类SKU商品的数据'''
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category_id=category_id)

    #排序
    filter_backends = [OrderingFilter]
    #指定排序字段
    ordering_fields = ('create_time','price','sales')

    # def get(self,request,category_id):
    #     '''
    #     self.kwargs:字典,保存从url地址中提取的所有命名参数
    #     根据第三级分类ID获取分类SKU商品的数据
    #     １.根据‘category_id’获取分类SKU商品的数据
    #     ２.将商品的数据序列化并返回
    #     '''
    #     # １.根据‘category_id’获取分类SKU商品的数据
    #     # skus = SKU.objects.filter(category_id=category_id)
    #     skus = self.get_queryset()
    #
    #     # ２.将商品的数据序列化并返回
    #     serializer = self.get_serializer(skus,many=True)
    #     return Response(serializer.data)


# 用户全部订单
# GET /orders/
# class AllOrdersView(APIView):
#     # 用户登陆权限认证
#     # permission_classes = [IsAuthenticated]
#
#     def get(self, request):
#         # 获取用户订单基本信息
#         user = request.user
#         ser_order = AllOrdersSerializer(user)
#
#         # 组织返回数据
#         orders_data = ser_order.data['orderinfo_set']
#         results = []
#         try:
#             # 将订单查询集转换为列表
#             orders_data = eval(json.dumps(orders_data))
#
#             # 重新组织返回数据体
#             for dict in orders_data:
#
#                 # 获取订单内商品详情
#                 skus = OrderGoods.objects.filter(id__in=dict['skus'])
#                 ser_skus = AllSkuSerializer(skus, many=True)
#                 skus_data = ser_skus.data
#
#                 # 将订单内商品详情查询集转换为列表
#                 skus_data = eval(json.dumps(skus_data))
#
#                 # 遍历skus_data, 组织sku中单个商品信息
#                 for item in skus_data:
#                     # 获取单个商品对象
#                     sku_obj = SKU.objects.get(id=item['sku'])
#
#                     # 序列化获取单个商品信息
#                     ser_sku = SingleSkuSerializer(sku_obj)
#
#                     # 修改数据
#                     item['sku'] = ser_sku.data
#
#                 # 添加新键值对
#                 dict['skus'] = skus_data
#
#                 # 向列表中添加数据
#                 results.append(dict)
#
#         except Exception as e:
#             return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)
#
#         data = {
#             'count': len(results),
#             'results': results
#         }
#
#         # 返回响应
#         return Response(data, status=status.HTTP_200_OK)


class AllOrdersView(ListAPIView):
    # 用户登陆权限认证
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        return OrderListSerializers

    def get_queryset(self):
        user = self.request.user
        return OrderInfo.objects.filter(user=user).order_by('-create_time')

